package com.easy.auth.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;

import java.util.Date;
import java.util.Map;
import java.util.Set;

public class TokenUtil {
    public static final String TOKEN_HEADER = "Authorization";

    public static final String TYPE = "TYPE";//user   admin
    public static final String TYPE_USER = "user";
    public static final String TYPE_ADMIN = "admin";
    public static final String USERID = "userid";//userid
    public static final String ADMINID = "adminid";

    /**
     * 签名  每次重启服务签名都会动态生成
     */
    public static final String SECRET_KEY = "Easy";
    /**
     * token有效时间
     */
    private static final long EXPIRATION = 86400000; // 24小时

    /**
     * 生成token
     *
     * @param map 需要加载的数据
     * @return
     */
    public static String generateToken(Map<String, Object> map) {
        JWT jwt = JWT.create();
        Set<String> keys = map.keySet();
        for (String key : keys) {
            jwt.setPayload(key, map.get(key));
        }
        jwt.setExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION));
        String token = jwt.setKey(SECRET_KEY.getBytes()).sign();
        return token;
    }

    /**
     * 获取token中的信息
     * @param token
     * @param key
     * @return
     */
    public static Object getPayload(String token, String key) {
        JWT jwt = cn.hutool.jwt.JWTUtil.parseToken(token);
        Object payload =jwt.getPayload(key);
        return payload;
    }

    public static boolean verifyToken(String token) {
        //验证签名
        if (!JWTUtil.verify(token, SECRET_KEY.getBytes())) {
            throw new RuntimeException("签名异常");
        }
        try {
            JWTValidator.of(token).validateDate();
        } catch (Exception e) {
            throw new RuntimeException("签名过期");
        }
        return true;
    }
}
